<?php

namespace App\Http\Controllers;

use App\Libraries\googleYzm\GoogleAuthenticator;
use App\Models\MembersModel;
use Illuminate\Http\Request;
use App\Models\AdminUserModel as AdminUser;
use App\Models\AdminUserTokenModel as AdminToken;
use Illuminate\Support\Facades\DB;

class IndexController extends Controller
{
    public $List = [];

    public function Index(Request $request)
    {

    }

    public function statistics(Request $request)
    {
        error_reporting(0);
        $date = (int)$request->input('date');
        switch ($date) {
            case 2:
                $today   = mktime(0, 0, 0, date('m'), date('d'), date('Y'));
                $between = $this->createBetween($today, 86400);
                $date    = $this->creatDate('m-d', $between, 86400);
                break;
            case 3: //按最近几个星期
                $w       = date('w') ? date('w') : 7;
                $toweek  = mktime(0, 0, 0, date('m'), date('d') - $w + 1, date('Y'));
                $between = $this->createBetween($toweek, 604800);
                $date    = $this->creatDate('m-d', $between, 604800);
                break;
            case 4: //按最近几个月
                $this->createBetweenMonth();
                $between = $this->createBetweenMonth();
                $date    = $this->creatDateMonth($between);
                break;

            default:
                $tohour  = mktime(date('H'), 0, 0, date('m'), date('d'), date('Y'));
                $between = $this->createBetween($tohour, 3600);
                $date    = $this->creatDate('H:i', $between, 3600);
                break;
        }
        $member    = [];
        $interview = [];
        $course    = [];
        foreach ($between as $k => $v) {
            $member[]    = DB::table('member')->whereBetween('create_time', $v)->count();
            $interview[] = DB::table('interview')->whereBetween('create_time', $v)->count();
            $course[]    = DB::table('course')->whereBetween('create_time', $v)->count();
        }
        $list['between']   = $between;
        $list['date']      = $date;
        $list['member']    = $member;
        $list['interview'] = $interview;
        $list['course']    = $course;
        return self::returnMsg($list);
    }


    //用户信息
    public function userInfo(Request $request)
    {
        $uid   = $request->get('uid');
        $admin = AdminUser::where('Id', $uid)->first();
        $data  = [
            'roles'        => $admin->roles_item,
            'avatar'       => $admin->Avatar,
            'introduction' => $admin->Introduction,
            'name'         => $admin->Name,
        ];
        return self::returnMsg($data, '', 20000);
    }

    //登录
    public function Login(Request $request)
    {
        $name     = trim($request->input('username'));
        $password = trim($request->input('password'));
        $user     = AdminUser::GetByName($name);
        if (empty($user)) return self::returnMsg([], '不存在管理员', 20000);

        /**
         * 谷歌验证码
         */
        $verification = trim($request->input('verification'));
        if (empty($verification)) {
            return self::returnMsg([], '请输入验证码', 20003);
        } else {
            //return self::returnMsg(AdminUser::get());
//            $google = new GoogleAuthenticator();
//            $code   = $google->getCode($user->google_secret);
//            if ($code !== $verification)
//                return self::errorMsg('验证码不正确');
        }

        if (md5($password) != $user->Password) return self::returnMsg([], '账号或密码错误', 20000);

        //生成Token
        $token = self::MakeToken($user->Id);
        $has   = AdminToken::GetByUid($user->Id);
        if (empty($has)) {
            $res = DB::table('adminusertoken')->insert([
                'Token'      => $token,
                'ExpireTime' => (3600 * AdminToken::EXPIRE_HOUR) + time(),
                'FlushTime'  => time(),
                'AdminId'    => $user->Id,
            ]);
        } else {
            $res = DB::table('adminusertoken')->where('AdminId', $user->Id)->update([
                'Token'      => $token,
                'ExpireTime' => (3600 * AdminToken::EXPIRE_HOUR) + time(),
                'FlushTime'  => time(),
            ]);
        }
        if (empty($res)) return self::returnMsg([], '登录失败，请稍后再试', 20000);
        //Token加密
        $encryptToken = self::TokenEncrypt($user->Id, $token);
        return self::returnMsg(['Token' => $encryptToken], '', 20000);
    }

    //退出登录
    public function Logout(Request $request)
    {
        $uid = $request->get('uid');
        DB::table('adminusertoken')->where('AdminId', $uid)->delete();
        return self::returnMsg();
    }

    private function test(Request $request)
    {

        $google     = new GoogleAuthenticator();
        $new_secret = $google->createSecret();
        echo "新的秘钥：" . $google->createSecret() . '<br/>';
        $list = DB::table('AdminUser')->get()->toArray();
        dump($list);
        $new = $request->input('new');
        if (!empty($new)) {
            $username = $request->input('name');
            if (empty($username)) {
                echo "请填入需要修改的用户名:<br/>";
                die();
            }
            $result = DB::table('AdminUser')->where('Name', '=', $username)->update(['google_secret' => $new_secret]);
            if ($result) {
                echo $username . "新的秘钥：" . $new_secret . '<br/>';
            } else {
                echo "秘钥没有更新成功,可能没有该用户";
            }
        }

    }

}
